<template>
  <div class="search-container">
    <span>搜索项目</span>
    <el-input v-model="inputProject" @input="handleBlurSeach" style="width: 200px; margin-left: 10px "
      placeholder="输入项目名称" clearable><template #prefix>
        <el-icon class="el-input__icon">
          <search />
        </el-icon>
      </template></el-input>
    <el-button class="common-button" @click="handleSearchProject" type="primary">查找</el-button>
  </div>


  <div class="table-container">
    <!-- 项目表 -->
    <el-table :data="flexProejctArray" style="width: 49%; height: 50vh" :header-cell-style="headerCellStyle">
      <el-table-column fixed type="index" width="100" label="序号" align="center">
      </el-table-column>
      <el-table-column prop="ProjectName" label="项目名称" align="center" show-overflow-tooltip />
      <el-table-column prop="QrcodeStr" label="项目编号" align="center" show-overflow-tooltip />
      <el-table-column fixed="right" label="操作" align="center" min-width="220">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleSample(scope.$index)">查询样品</el-button>
          <el-button type="warning" size="small" @click="handlerAddCode(scope.$index)">构建编码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 样品表 -->
    <el-table :data="sampleList" style="width: 49%; height: 50vh" :header-cell-style="headerCellStyle2">
      <el-table-column fixed type="index" width="110" label="序号" align="center" />
      <el-table-column fixed prop="sampleName" label="样品名称" align="center" show-overflow-tooltip />
      <el-table-column prop="sampleCode" label="样品编号" align="center" show-overflow-tooltip />
      <el-table-column prop="limit" label="检出限" align="center" />
      <el-table-column fixed="right" label="操作" align="center" width="100">
        <template #default="scope">
          <el-button type="warning" size="small" @click="handlerAddCodeSample(scope.$index)">构建编码</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-divider>
  </el-divider>
  <!-- 构建二维码区域 -->
  <div class="code-construct">
    <el-table :data="buildCard" style="width: 39%; height: 20vh" :header-cell-style="headerCellStyle2">
      <el-table-column fixed type="index" width="100" label="通道" align="center" />
      <el-table-column prop="ProjectName" label="项目名称" min-width="120" align="center" show-overflow-tooltip />
      <el-table-column prop="QrcodeStr" label="项目编号" min-width="120" align="center" show-overflow-tooltip />
      <el-table-column prop="sampleCode" label="样品编号" min-width="120" align="center" show-overflow-tooltip />
      <el-table-column prop="sampleName" label="样品名称" align="center" min-width="120" />
      <el-table-column fixed="right" label="操作" align="center" min-width="120">
        <template #default="scope">
          <el-button type="danger" size="small" @click="handleDelete(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="buttons">
      <el-button type="primary" width="100%" @click="handleConstruct()">构建二维码<el-icon class="el-icon--right">
          <CaretRight />
        </el-icon></el-button>
      <el-button class="exportButton" type="success" width="100%" @click="handleExport()">导出数据表<el-icon
          style="margin-left: 5px;">
          <Document />
        </el-icon></el-button>
    </div>



    <!-- 构建二维码 -->
    <el-table class="c-list" @selection-change="handleSelectionChange" :data="codeList" style="width: 55%; height: 20vh"
      :header-cell-style="headerCellStyle2">
      <el-table-column fixed type="selection" max-width="55" />
      <el-table-column fixed type="index" width="100" label="产品序号" align="center" />
      <el-table-column prop="fullQrStr" label="完整编号" align="center" min-width="400" show-overflow-tooltip />
      <el-table-column prop="cardType" label="卡类型" align="center" />
      <el-table-column label="备注" align="center">
        <template #default="scope">
          <el-input v-model="scope.row.inputComment" placeholder="选填信息"></el-input>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" min-width="120">
        <template #default="scope">
          <el-button type="danger" size="small" @click="handleDeleteCard(scope.$index)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
  </div>
</template>

<style>
.table-container {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  overflow-y: auto;
  /* 启用垂直滚动 */
  max-height: 90vh;
  /* 使用相对单位适配不同显示器和浏览器的尺寸 */
}


.mdivider {
  @apply bg-dark-800
}

.search-container {
  display: flex;
  margin-left: 10px;
  align-items: center;
}

.search-container .common-button {
  width: 80px;
  height: auto;
  @apply bg-indigo-500;
  margin-left: 10px;
}

.code-construct {
  display: flex;
  align-items: center;
}

.code-construct .buttons {
  display: flex;
  justify-content: space-around;
  flex-direction: column;
  width: 10%;
  height: 20vh;

  @apply ml-5
}

.code-construct .buttons .exportButton {
  @apply ml-0
}

.code-construct .c-list {
  @apply ml-5
}
</style>

<script setup>
import { getProjectList, sampleInfoByProject } from '../../api/projects_man.js'
import { InfoToast } from "../../composables/toastUtils";
import { ref } from 'vue';
import { utils, write } from 'xlsx';
import { saveAs } from 'file-saver';

// 内连样式
const headerCellStyle = {
  backgroundColor: '#6366F1',
  color: '#ffffff',
  textAlign: 'center'
};

const headerCellStyle2 = {
  backgroundColor: '#818CF8',
  color: '#ffffff',
  textAlign: 'center'
}


// 项目列表信息
// 初始化一个空的 Map 方便查找对应的项目
const projectsMap = new Map();
const projects = ref([]);
const flexProejctArray = ref([]);

// 样品列表信息
const sampleList = ref([])

// 构建二维码的信息
const buildCard = ref([])

// 所有构建完成的二维码信息列表，待导出的
const constructedList = ref([])


// 输入框信息
const inputProject = ref('')
const inputComment = ref('')

// 生成好的样品编码列表


var cardParams = {
  fullQrStr: String,
  cardType: String,
  inputComment: String,
  fullQrStr: String,
  fullString: String
}
const codeList = ref([])
const selectedCardParams = ref([])



// 加载项目信息
getProjectList()
  .then((res) => {
    //转换成Array
    projects.value = res.data
    res.data.forEach(p => {
      projectsMap.set(p.ProjectName, p)
    })
    flexProejctArray.value = projects.value

  })
  .catch((err) => {
    console.log(err)
  });

// 根据项目名称获取信息
function handleSearchProject() {
  if (inputProject.value == "") {
    InfoToast("请输入项目名称", "info")
    flexProejctArray.value = projects.value
  } else if (projectsMap.has(inputProject.value)) {  // 存在项目
    flexProejctArray.value = []
    flexProejctArray.value.push(projectsMap.get(inputProject.value));
  } else {
    InfoToast("不存在项目请确认项目名称", "info")
  }
}

// 模糊查询当前输入的项目名称
function handleBlurSeach() {
  flexProejctArray.value = []
  if (inputProject.value == "") { // 如果取消键入文本，就放回全部的内容
    flexProejctArray.value = projects.value
  } else {
    projects.value.forEach((p) => {
      if (p.ProjectName.includes(inputProject.value)) {
        flexProejctArray.value.push(p)
      }
    });
  }
}

// 点击搜索关联样品
const handleSample = (index) => {
  sampleInfoByProject(flexProejctArray.value[index].ProjectName)
    .then((res) => {
      sampleList.value = res.data
      // console.log(res.data)
    })
    .catch((err) => {
      InfoToast(err, "error")
    })
}

// 加入项目进行编码
const handlerAddCode = (index) => {
  let record = flexProejctArray.value[index]
  let channel = {
    QrcodeStr: record.QrcodeStr,
    sampleCode: "",
    ProjectName: record.ProjectName,
  }
  buildCard.value.push(channel)

}

// 加入样品
const handlerAddCodeSample = (index) => {
  let record = sampleList.value[index]
  let project = projectsMap.get(record.relatedProject)
  let channel = {
    QrcodeStr: project.QrcodeStr,
    sampleCode: record.sampleCode,
    ProjectName: project.ProjectName,
    sampleName: record.sampleName
  }
  buildCard.value.push(channel)
}

// 删除通道信息
const handleDelete = (index) => {
  buildCard.value.splice(index, 1)
}

// 删除构建好的二维码表
const handleDeleteCard = (index) => {
  codeList.value.splice(index, 1)
}

// 构建二维码列表
const handleConstruct = () => {
  // 基本逻辑是，如果样品编号存在，就直接用样品编号拼凑
  // 如果样品编号不存在，就用项目编号拼凑
  let arrLength = buildCard.value.length
  if (arrLength > 0) {

    let fullCode = buildCard.value.map(c => {
      let codePart = '';
      if (c.sampleCode.length > 0) {
        codePart = c.sampleCode;
      } else {
        codePart = c.QrcodeStr;
      }
      return codePart;
    }).join('.');

    let fullString = buildCard.value.map(c => {
      let pNmae = c.ProjectName;
      if (c.sampleCode.length > 0) {
        pNmae += "(" + c.sampleName +")";
      }
      return pNmae;
    }).join(',');

    /* buildCard.value.forEach(c => {
      fullCode += c.QrcodeStr
      if (c.sampleCode.length > 0) { // 如果设置样品编码的
        fullCode += "\:" + c.sampleCode;
      }
      if ()
        fullCode += ","

    }); */
    const str = '91320506313704527A';
    const substr = str.slice(8, 17); // 获取第9到第17位（索引为8到16）的子字符串

    // 待导出的二维码编码
    cardParams = {
      cardType: buildCard.value.length + '联卡',
      inputComment: inputComment.value,
      fullQrStr: substr + '|' +fullCode + "|" + Date.now().toString().slice(-8) + "\_01",
      fullString: fullString
    }
    codeList.value.push(cardParams)
  }
}

// 导出excel表中
const handleExport = () => {
  const data = [
    ['产品二维码构建表'],
    ['序号', '联卡类型', '项目与样品全称', '编码', '备注']
  ];
  if (selectedCardParams.value.length > 0) {
    selectedCardParams.value.forEach((c, index) => {
      let temp = []
      temp.push(index + 1);
      temp.push(c.cardType);
      temp.push(c.fullString);
      temp.push(c.fullQrStr);
      temp.push(c.inputComment);
      data.push(temp)
    })
    const ws = utils.aoa_to_sheet(data);
    const wb = utils.book_new();
    utils.book_append_sheet(wb, ws, 'Sheet1');
    const wbout = write(wb, { bookType: 'xlsx', type: 'array' });
    saveAs(new Blob([wbout], { type: 'application/octet-stream' }), Date.now().toString() + '\.xlsx');
  }

}

// 某一行的选中或取消选中
const handleSelectionChange = (selectedKeys) => {
  selectedCardParams.value = []
  selectedKeys.forEach((item) => {
    if (item) {
      selectedCardParams.value.push(item)
    }
  })
}

</script>
